package com.atguigu.yygh.order.service.impl;

import com.atguigu.yygh.common.utils.HttpRequestHelper;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.enums.RefundStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.service.PaymentInfoService;
import com.atguigu.yygh.order.service.RefundInfoService;
import com.atguigu.yygh.order.service.WeiPayService;
import com.atguigu.yygh.order.utils.ConstantPropertiesUtils;
import com.atguigu.yygh.order.utils.HttpClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author:hx
 * @DateTime:2022/11/19 10:23
 * @Description:
 */
@Service
public class WeiPayServiceImpl implements WeiPayService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private RefundInfoService refundInfoService;

    @Override
    public String createNative(Long orderId) {
        OrderInfo orderInfo = orderInfoService.getById(orderId);


        PaymentInfo paymentInfo = new PaymentInfo();

        paymentInfoService.savePaymentInfo(orderId);

        HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

        Map<String,String> map = new HashMap<>();
        map.put("appid", ConstantPropertiesUtils.APPID);
        map.put("mch_id",ConstantPropertiesUtils.PARTNER);
        map.put("nonce_str", WXPayUtil.generateNonceStr());
        map.put("body","尚医通预约挂号费用");
        map.put("out_trade_no",orderInfo.getOutTradeNo());
        map.put("total_fee","1");
        map.put("spbill_create_ip","127.0.0.1");
        map.put("notify_url","127.0.0.1");
        map.put("trade_type","NATIVE");
        try {

            httpClient.setXmlParam(WXPayUtil.generateSignedXml(map, ConstantPropertiesUtils.PARTNERKEY));
            httpClient.setHttps(true);
            httpClient.post();

            String content = httpClient.getContent();
            Map<String, String> result = WXPayUtil.xmlToMap(content);

            if (result.get("result_code").equalsIgnoreCase("success")){
                return result.get("code_url");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    @Override
    public String queryPayStatus(Long orderId) {

        OrderInfo orderInfo = orderInfoService.getById(orderId);

        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",orderId);
        PaymentInfo paymentInfo = paymentInfoService.getOne(queryWrapper);

        Map<String,String> map = new HashMap<>();
        map.put("appid",ConstantPropertiesUtils.APPID);
        map.put("mch_id",ConstantPropertiesUtils.PARTNER);
        map.put("out_trade_no",paymentInfo.getOutTradeNo());
        map.put("nonce_str",WXPayUtil.generateNonceStr());

        try {
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(map,ConstantPropertiesUtils.PARTNERKEY));
            httpClient.setHttps(true);
            httpClient.post();

            String content = httpClient.getContent();
            Map<String, String> xmlToMap = WXPayUtil.xmlToMap(content);

            if (xmlToMap.get("trade_state").equalsIgnoreCase(WXPayConstants.SUCCESS)){
                //修改订单信息
                orderInfoService.updateStatus(OrderStatusEnum.PAID,orderId);
                //修改支付信息
                paymentInfoService.updatePaymentInfo(xmlToMap,orderId);
                //通知第三方医院

                Map<String,Object> paramMap=new HashMap<>();
                paramMap.put("hoscode",orderInfo.getHoscode());
                paramMap.put("hosRecordId",orderInfo.getHosRecordId());
                HttpRequestHelper.sendRequest(paramMap,"http://localhost:9998/order/updatePayStatus");
                //返回支付状态
                return "已支付";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回支付状态
        return "支付中";
    }

    @Override
    public Boolean refund(Long orderId) {

        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",orderId);
        PaymentInfo paymentInfo = paymentInfoService.getOne(queryWrapper);
        RefundInfo refundInfo = refundInfoService.saveRefundInfo(null,paymentInfo);
        if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()){
            return false;
        }

        HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
        Map<String,String> map = new HashMap<>();
        map.put("appid",ConstantPropertiesUtils.APPID);
        map.put("mch_id",ConstantPropertiesUtils.PARTNER);
        map.put("nonce_str",WXPayUtil.generateNonceStr());
        map.put("transaction_id",paymentInfo.getTradeNo());

        map.put("out_refund_no","tk"+paymentInfo.getOutTradeNo());

        map.put("total_fee","1");
        map.put("refund_fee","1");

        try {
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(map,ConstantPropertiesUtils.PARTNERKEY));
            httpClient.setHttps(true);
            httpClient.setCert(true);
            httpClient.setCertPassword(ConstantPropertiesUtils.PARTNER);
            httpClient.post();

            String content = httpClient.getContent();
            Map<String, String> xmlToMap = WXPayUtil.xmlToMap(content);

            if (xmlToMap.get("return_code").equalsIgnoreCase(WXPayConstants.SUCCESS)){
                refundInfoService.saveRefundInfo(xmlToMap,paymentInfo);
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}
